// Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.

// 构造客户端请求
package cloudresource

import (
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/global"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/config"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/httphandler"
	as "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/as/v1"
	ecs "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2"
	iam "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iam/v3"
	smn "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/smn/v2"
	"scase.io/application-auto-scaling-service/pkg/utils/logger"

	"scase.io/application-auto-scaling-service/pkg/setting"
)

const defaultSdkRetries = 3

var httpConfig = config.DefaultHttpConfig().
	WithIgnoreSSLVerification(true).
	WithHttpHandler(httphandler.
		NewHttpHandler().
		AddMonitorHandler(monitorHandler)).
	WithRetries(defaultSdkRetries)

var opIamCli *OpSvcIamCli

type OpSvcIamCli struct {
	iamCli *iam.IamClient
}

// InitOpSvcIamClient init op_svc iam client
func InitOpSvcIamClient() error {
	opIamCli = &OpSvcIamCli{iamCli: iam.NewIamClient(
		iam.IamClientBuilder().
			WithEndpoint(setting.CloudClientAsEndpoint).
			WithCredential(
				global.NewCredentialsBuilder().
					WithIamEndpointOverride(setting.CloudClientIamEndpoint).
					WithAk(string(setting.ServiceAk)).
					WithSk(string(setting.ServiceSk)).
					WithDomainId(setting.ServiceDomainId).
					Build()).
			WithHttpConfig(httpConfig).
			Build())}
	return nil
}

func newAsClient(cred auth.ICredential, projectId string) *as.AsClient {
	return as.NewAsClient(
		as.AsClientBuilder().
			WithEndpoint(setting.CloudClientAsEndpoint).
			WithCredential(cred).
			WithHttpConfig(httpConfig).
			Build())
}

func newEcsClient(cred auth.ICredential, projectId string) *ecs.EcsClient {
	return ecs.NewEcsClient(
		ecs.EcsClientBuilder().
			WithEndpoint(setting.CloudClientEcsEndpoint).
			WithCredential(cred).
			WithHttpConfig(httpConfig).
			Build())
}

func newSmnClient(cred auth.ICredential, projectId string) *smn.SmnClient {
	return smn.NewSmnClient(
		smn.SmnClientBuilder().
			WithEndpoint(setting.CloudClientSmnEndpoint).
			WithCredential(cred).
			WithHttpConfig(httpConfig).
			Build())
}

func monitorHandler(monitor *httphandler.MonitorMetric) {
	logger.C.Info("service_call_event: %+v", *monitor)
}
